from flask import render_template
from . import basic_bp
from sqlalchemy import func
from exts import db
from apps.goods.models import Goods
from apps.cates.models import GoodsCategory
from apps.members.models import Member
from apps.orders.models import Order
import os
from exts import celery_app


@basic_bp.before_request
def before_request():
    current_dir = os.path.dirname(__file__)
    parent_dir = os.path.dirname(current_dir)
    filename = f'{parent_dir}/templates/static/index.html'
    # print("ok")
    if os.path.isfile(filename):
        return render_template("static/index.html")


@basic_bp.route('/index')
def index():
    order_count = db.session.query(func.count(Order.id)).scalar()
    member_count = db.session.query(func.count(Member.id)).scalar()
    goods_count = db.session.query(func.count(Goods.id)).scalar()

    infos = GoodsCategory.query.join(Goods, GoodsCategory.cat_id == Goods.category_id).with_entities(GoodsCategory.name,
                                                                                                     func.sum(
                                                                                                         Goods.amount)).group_by(
        GoodsCategory.name).all()
    goods_labels = [info[0] for info in infos]
    goods_datas = [int(info[1]) for info in infos]

    maleCount = Member.query.filter(Member.sex == 1).count()
    femaleCount = Member.query.filter(Member.sex == 0).count()
    return render_template('shop/index.html', order_count=order_count, member_count=member_count,
                           goods_count=goods_count,
                           goods_labels=goods_labels, goods_datas=goods_datas, maleCount=maleCount,
                           femaleCount=femaleCount)


@celery_app.task
def build_index():
    content = index()
    current_dir = os.path.dirname(__file__)
    parent_dir = os.path.dirname(current_dir)
    with open(f'{parent_dir}/templates/static/index.html', mode='w', encoding='utf-8') as file:
        file.write(content)
    return "首页静态化处理完成"
